package com.itany.order.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.itany.constant.Constant;
import com.itany.dao.OrderMapper;
import com.itany.exception.RequestParamsException;
import com.itany.order.service.IOrderService;
import com.itany.pojo.Order;
import com.itany.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.table.TableRowSorter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


@Service
@com.alibaba.dubbo.config.annotation.Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class OrderServiceImpl implements IOrderService {


    @Autowired
    StringRedisTemplate template;

    @Autowired(required = false)
    OrderMapper orderMapper;

//    @Autowired(required = false)
//    OrderBookMapper orderBookMapper;


    @Autowired
    public AlipayClient alipayClient;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public String getQrCode() {
        //二维码字符串
        String qrCode="";
        try {

            //TODO:订单编号尚未生成
            String no = System.currentTimeMillis()+"";
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            model.setOutTradeNo(no);
            model.setTotalAmount("0.01");
            model.setSubject("天下画集");
            request.setNotifyUrl("http://zhachao.free.idcfengye.com/order/order/paySuccess/"+no);
            request.setBizModel(model);
            AlipayTradePrecreateResponse response =  alipayClient.execute(request);
            if(response.isSuccess()){
                qrCode=response.getQrCode();
                System.out.println("调用成功:"+qrCode);
            }else {
                System.out.println("调用失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return qrCode;
    }

    /**
     * 生成订单
     *
     * @param bookIdArray
     */
    @Override
    public Order generateOrder(List<String> bookIdArray,User user) throws RequestParamsException {
        if(bookIdArray.isEmpty()){
            throw new RequestParamsException("请求参数缺失");
        }
        Map<Object, Object> entries = template.opsForHash().entries(Constant.SHOPPING_CART_REDIS_KEY + user.getId());
        List<String> pricesArray = new ArrayList<>();
        for (String bookId : bookIdArray){
            Map<Object, Object> bookmap = template.opsForHash().entries("book" + bookId);
            String purchasenums  = (String) entries.get(bookId);

            BigDecimal price = new BigDecimal((String) bookmap.get("price"));
            BigDecimal totalmoney = new BigDecimal(purchasenums).multiply(price).setScale(2, RoundingMode.HALF_UP);
            pricesArray.add(totalmoney+"");

        }
        Order order = new Order();
        order.setNo(UUID.randomUUID().toString());
        order.setAlipayno(SecureUtil.md5(String.valueOf(System.currentTimeMillis())));
        order.setUser(user);
        order.setFlag(Constant.ENABLE_STATUS);
        order.setPrice(countMoney(pricesArray));
        orderMapper.insertOrder(order);
//        Integer orderId = order.getId();
//        orderBookMapper.insertOrderBook(orderId);

        return  order;
    }


    /**
     * 获取购物车
     *
     * @return
     */
    @Override
    public List<Map<Object, Object>> findshoppingcart(User user) {
        List<Map<Object, Object>> purchasebooks = new ArrayList<>();
        Map<Object, Object> entries = template.opsForHash().entries(Constant.SHOPPING_CART_REDIS_KEY + user.getId());
        Set<Object> books = entries.keySet();
        if(!books.isEmpty()) {
            for (Object bookId : books) {
                String bookIdStr = null;
                if (bookId instanceof String) {
                    bookIdStr = (String) bookId;
                }
                Map<Object, Object> bookmap = template.opsForHash().entries("book" + bookIdStr);
                String purchasenums  = (String) entries.get(bookId);
                BigDecimal price = new BigDecimal((String) bookmap.get("price"));
                bookmap.put("purchasenums",purchasenums );
                BigDecimal totalmoney = new BigDecimal(purchasenums).multiply(price).setScale(2, RoundingMode.HALF_UP);
                bookmap.put("totalmoney",totalmoney);
                bookmap.put("bookId",bookIdStr);
                purchasebooks.add(bookmap);
            }
        }
        return purchasebooks.isEmpty() ? null : purchasebooks;

    }

    /**
     * 计算总价格
     *
     * @param
     * @return
     */
    @Override
    public BigDecimal countMoney(List<String> pricesArray) {
        BigDecimal paymentAmount = new BigDecimal(0);
        for (int i = 0; i < pricesArray.size(); i++) {
            BigDecimal price = new BigDecimal(pricesArray.get(i));
            paymentAmount = paymentAmount.add(price).setScale(2,RoundingMode.HALF_UP);
        }
        return paymentAmount;
    }


}
